import axios from 'axios';
import { Indicator, Toast } from 'mint-ui';

import Store from '@/store/index';
// import * as types from './store/types'
// import router from './router'

// axios 配置
const csrfHeaderName = 'X-CSRF-Token';
axios.defaults.timeout = 5000;
// axios.defaults.baseURL = 'http://localhost.com:8081/rpc';
axios.defaults.baseURL = 'http://192.168.250.216:8081/rpc';
// axios.defaults.baseURL = 'https://www.easy-mock.com/mock/59ee94387f0b754c4da895cb/api/rpc';
axios.defaults.withCredentials = false; // auto cookie
axios.defaults.auth = {
  username: 'e2b6abfc-3576-4fe7-9f69-1f647169a827',
  password: 'e24e45c9-a7bc-4248-be78-17b32bea1544',
};
// http request 拦截器
axios.interceptors.request.use(
  (config) => {
    Indicator.open({
      text: '加载中...',
      spinnerType: 'snake',
    });
    if (Store.getters.getToken) {
      // eslint-disable-next-line
      config.headers[csrfHeaderName] = Store.getters.getToken;
    }
    return config;
  },
  (err) => {
    Indicator.close();
    Promise.reject(err);
  });

// http response 拦截器
axios.interceptors.response.use((response) => {
  Indicator.close();
  return response;
},
  (error) => {
    Indicator.close();
    // console.log('error.response', error.response);
    if (error.response) {
      const status = error.response.status;
      if (error.response.data) {
        Toast(error.response.data.detail);
      } else {
        Toast(error.message);
      }
      switch (status) {
        case 401:
         // 401 清除token信息并跳转到登录页面
          Store.commit('LOGOUT');
          // router.replace({
          //  path: '/login',
          //  query: {redirect: router.currentRoute.fullPath},
          // });
          break;
        case 500:
          // Toast('服务器错误');
          break;
        default:
          Toast(error.message);
          break;
      }
    } else if (error.request) {
      console.log('error.request', error.request);
      Toast(error.message);
    }
    return Promise.reject(error);
  });

export default axios;
